package com.augurit.gis.flex;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;



public class FlexServlet extends BaseServlet{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private static final String BEAN_ID="beanId";
	private static final String CLIENT = "client";
	private static final String FLEX = "flex";


	/**
	 * 所能处理的请求URL：
	 * flexServlet?client=flex&beanId=[beanId]&method=[method]&params=[json]...;
	 */
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		try {
//			request.setCharacterEncoding("UTF-8");
//		} catch (UnsupportedEncodingException e2) {
//			// TODO Auto-generated catch block
//			e2.printStackTrace();
//		}
		//response.setContentType("text/xml;charset=utf-8");
		String callType = request.getParameter("callType");
		String client = request.getParameter(CLIENT);
		if(client!=null && client.equals(FLEX)){
			if(callType == null || callType.equals("") || callType.equals("byHashMap")){
				callServiceByHashMap(request,response);
			}else{
				callServiceByDynamicObject(request,response);
			}
		}
	}
   
	
	

	@SuppressWarnings("unchecked")
	private void callServiceByHashMap(HttpServletRequest request,
			HttpServletResponse response) {
		System.out.println("in flex servlet.callServiceByHashMap...1");
		String beanId = request.getParameter(BEAN_ID);
		//System.out.println(beanId);
		if(beanId!=null){
			Object bean = getBean(beanId);
			String methodName = request.getParameter("method");
			if(bean!=null && methodName!=null){
				try {
					Map<String, ?> map = request.getParameterMap();
					//参数列表
					Map<String, String> paramMap = new HashMap<String, String>();
					Iterator<String> itr = map.keySet().iterator();
					while(itr.hasNext()){
						String paramName = (String)itr.next();
						if(!paramName.equals(BEAN_ID) && !paramName.equals(CLIENT) && !paramName.equals("method")){
							String paramValue = request.getParameter(paramName);
							paramMap.put(paramName, paramValue);
							System.out.println(paramName+"="+paramValue);
						}
					}
					Method method = bean.getClass().getMethod(methodName,Map.class);
					Object returnObject = method.invoke(bean,paramMap);
					writeJson2Client(response, returnObject);
				} catch (Exception e) {
					e.printStackTrace();
				} 
				
			}
		}
		
	}


	/**
	 * @param request
	 * @param response
	 */
	private void callServiceByDynamicObject(HttpServletRequest request,
			HttpServletResponse response) {
		System.out.println("in flex servlet.callServiceByDynamicObject...2");
		String beanId = request.getParameter(BEAN_ID);
		if(beanId!=null){
			Object bean = getBean(beanId);//到配置文件获取节点是Bean的连接
			String methodName = request.getParameter("method");
			if(bean!=null && methodName!=null){
				String json =request.getParameter("params");
				System.out.println("json="+json);
				try {
					json=new String(json.getBytes("ISO-8859-1"),"UTF-8");
				} catch (UnsupportedEncodingException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} 
				System.out.println("json="+json);
				if(json!=null && !json.equals("[]") && !json.equals("[{}]")){
					try {
						JSONArray jsonArray = JSONArray.fromObject(json);
						Class<?>[] paramClasses = new Class[jsonArray.size()];
						Object[] paramObjects = new Object[jsonArray.size()];
						for (int i = 0; i < jsonArray.size(); i++) {
							JSONObject object = jsonArray.getJSONObject(i);
							String value = object.getString("value");//得到传过来的参数中KEY为value的值
							String javaType = object.getString("javaType");
							String paramJavaType = null;
							if(object.containsKey("paramJavaType"))
							paramJavaType = object.getString("paramJavaType");
							//处理原始数据类型的情况
							if(javaType.equals(int.class.getName())){
								paramClasses[i] = int.class;
							} else if(javaType.equals(long.class.getName())){
								paramClasses[i] = long.class;
							} else if(javaType.equals(float.class.getName())){
								paramClasses[i] = float.class;
							} else if(javaType.equals(double.class.getName())){
								paramClasses[i] = double.class;
							} else if(javaType.equals(short.class.getName())){
								paramClasses[i] = short.class;
							} else if(javaType.equals(boolean.class.getName())){
								paramClasses[i] = boolean.class;
							} else if(javaType.equals(byte.class.getName())){
								paramClasses[i] = byte.class;
							}else if(paramJavaType == null || paramJavaType.equals("")){
								Class<?> clazz = Class.forName(javaType);
								if (clazz.getSuperclass() == BaseForm.class) {
									paramClasses[i] = BaseForm.class;
								} else {
									paramClasses[i] = clazz;
								}
							} else {
								paramClasses[i] = Class.forName(paramJavaType);
							}
//							Class<?> clazz = Class.forName(javaType);
//							if (paramJavaType == null || paramJavaType.equals("")) {
//								if (clazz.getSuperclass() == BaseForm.class) {
//									paramClasses[i] = BaseForm.class;
//								} else {
//									paramClasses[i] = Class.forName(javaType);
//								}
//							} else {
//								
//							}
							if (Long.class.getName().equals(javaType) || long.class.getName().equals(javaType)) {
								paramObjects[i] = new Long(value);
							} else if (Float.class.getName().equals(javaType) || float.class.getName().equals(javaType)) {
								paramObjects[i] = new Float(value);
							} else if (Double.class.getName().equals(javaType) || double.class.getName().equals(javaType)) {
								paramObjects[i] = new Double(value);
							} else if (Integer.class.getName().equals(javaType) || int.class.getName().equals(javaType)) {
								paramObjects[i] = new Integer(value);
							} else if (String.class.getName().equals(javaType)) {
								paramObjects[i] = new String(value);
							} else if (byte.class.getName().equals(javaType)) {
								paramObjects[i] = new byte[1];
							} else if (Boolean.class.getName().equals(javaType) || boolean.class.getName().equals(javaType)) {
								paramObjects[i] = new Boolean(value);
							} else if (Short.class.getName().equals(javaType) || short.class.getName().equals(javaType)) {
								paramObjects[i] = new Short(value);
							} else if (Date.class.getName().equals(javaType)) {
								paramObjects[i] = Utils.stringToDate(value,Utils.SIMPLE_DATE);
							} else {
								Object dto = JsonUtil.getDTO(value, Class.forName(javaType));
								paramObjects[i] = dto;
							}
						}
						Method method2 = bean.getClass().getMethod(methodName, paramClasses);
						Object returnObject = method2.invoke(bean, paramObjects);
						writeJson2Client(response, returnObject);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}else{
					try {
						Method method2 = bean.getClass().getMethod(methodName);
						Object returnObject = method2.invoke(bean);
						writeJson2Client(response, returnObject);
					} catch (Exception e) {
						e.printStackTrace();
					}
					
				}
			}
		}
		}


}
